package com.bnyy.medicalHousekeeper.moudle.message.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.bnyy.medicalHousekeeper.BuildConfig;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.base.BaseFragmentImpl;
import com.bnyy.medicalHousekeeper.bean.Customer;
import com.bnyy.medicalHousekeeper.moudle.message.activity.ChatMessageActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.CreateGroupChatActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.SelectContactActivity;
import com.bnyy.medicalHousekeeper.moudle.message.adapter.ContactAdapter;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.message.bean.Contact;
import com.bnyy.message.bean.ContactUser;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/11/8
 **/
public class MessageHomePageFragment extends BaseFragmentImpl {
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager2 viewPager;
    @BindView(R.id.tv_chat)
    TextView tvChat;

    private ActivityResultLauncher<Intent> launcher;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_message_home_page;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                Intent intent = result.getData();
                if (intent != null) {
                    ArrayList<Contact> contacts = (ArrayList<Contact>) intent.getSerializableExtra(SelectContactActivity.RESULT_SELECTED_CONTACTS);
                    if (contacts != null && contacts.size() > 0) {
                        ChatMessageActivity.show(mContext, contacts.get(0));
                    }
                }
            }
        });

        tvChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupWindow popupWindow = new PopupWindow(ScreenUtils.getScreenWidth() / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setOutsideTouchable(false);
                popupWindow.setBackgroundDrawable(new ColorDrawable());
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);

                int dp12 = SizeUtils.dp2px(12);

                RelativeLayout rlRoot = new RelativeLayout(mContext);
                rlRoot.setPadding(0, 0, 0, dp12);

                LinearLayout linearLayoutContent = new LinearLayout(mContext);
                linearLayoutContent.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                linearLayoutContent.setOrientation(LinearLayout.VERTICAL);

//                rlRoot.addView(linearLayoutContent);

                GradientDrawable bg = new GradientDrawable();
                bg.setCornerRadius(dp12);
                bg.setColor(Color.parseColor("#DB000000"));
                linearLayoutContent.setBackground(bg);

                TextView tvPrivateChat = new TextView(mContext);
                tvPrivateChat.setTextColor(Color.WHITE);
                tvPrivateChat.setText("发私信");
                tvPrivateChat.setGravity(Gravity.CENTER_VERTICAL);
                tvPrivateChat.setSingleLine(true);
                tvPrivateChat.setEllipsize(TextUtils.TruncateAt.END);
                tvPrivateChat.setPadding(dp12, dp12, dp12, dp12);
                Drawable drawablePrivateChat = ContextCompat.getDrawable(mContext, R.mipmap.icon_private_chat);
                drawablePrivateChat.setBounds(0, 0, drawablePrivateChat.getMinimumWidth(), drawablePrivateChat.getMinimumHeight());
                tvPrivateChat.setCompoundDrawables(drawablePrivateChat, null, null, null);
                tvPrivateChat.setCompoundDrawablePadding(dp12);
                tvPrivateChat.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        HashMap<String, Object> params = new HashMap<>();
                        params.put("page_index", 1);
                        params.put("page_size", 10000);
                        params.put("tag_type", 7);
                        requestManager.request(requestManager.mJavaRetrofitService.getCustomerList(RequestManager.getJsonRequestBody(params)),
                                new BaseObserverImpl<ArrayList<Customer>>(mContext) {
                                    @Override
                                    public void onSuccess(ArrayList<Customer> customers) {
                                        super.onSuccess(customers);
                                        popupWindow.dismiss();
                                        SelectContactActivity.show(
                                                mContext,
                                                "发私信",
                                                new ContactAdapter.ConstantItem(),
                                                new ArrayList<>(customers.stream()
                                                        .map(new Function<Customer, ContactUser>() {
                                                            @Override
                                                            public ContactUser apply(Customer customer) {
                                                                ContactUser contactUser = new Customer();
                                                                contactUser.setUser_img(customer.getUser_image());
                                                                contactUser.setUsername(customer.getUser_name());
                                                                contactUser.setRole_id(customer.getRole_id());
                                                                contactUser.setId(customer.getId());
                                                                return contactUser;
                                                            }
                                                        })
                                                        .collect(Collectors.toList())),
                                                launcher
                                        );
                                    }
                                });
                    }
                });
                linearLayoutContent.addView(tvPrivateChat);

                View divider = new View(mContext);
                divider.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(1)));
                divider.setBackgroundColor(ContextCompat.getColor(mContext, R.color.gray_light));
                divider.setPadding(dp12, 0, dp12, 0);
                linearLayoutContent.addView(divider);

                TextView tvCreateGroupChat = new TextView(mContext);
                tvCreateGroupChat.setTextColor(Color.WHITE);
                tvCreateGroupChat.setText("创建群聊");
                tvCreateGroupChat.setGravity(Gravity.CENTER_VERTICAL);
                tvCreateGroupChat.setSingleLine(true);
                tvCreateGroupChat.setEllipsize(TextUtils.TruncateAt.END);
                tvCreateGroupChat.setPadding(dp12, dp12, dp12, dp12);
                Drawable drawableCreateGroupChat = ContextCompat.getDrawable(mContext, R.mipmap.icon_group_chat);
                drawableCreateGroupChat.setBounds(0, 0, drawableCreateGroupChat.getMinimumWidth(), drawableCreateGroupChat.getMinimumHeight());
                tvCreateGroupChat.setCompoundDrawables(drawableCreateGroupChat, null, null, null);
                tvCreateGroupChat.setCompoundDrawablePadding(dp12);
                tvCreateGroupChat.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        BaseActivityImpl.show(mContext, CreateGroupChatActivity.class);
                    }
                });
                linearLayoutContent.addView(tvCreateGroupChat);

                popupWindow.setContentView(linearLayoutContent);

                popupWindow.showAsDropDown(tvChat, -dp12, 0, Gravity.RIGHT);
            }
        });

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                TextView tv = (TextView) tab.getCustomView();
                tv.setTextColor(ContextCompat.getColor(mContext, R.color.gray_text));
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                tv.getPaint().setFakeBoldText(true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tv = (TextView) tab.getCustomView();
                tv.setTextColor(ContextCompat.getColor(mContext, R.color.gray_light));
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                tv.getPaint().setFakeBoldText(false);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        if (BuildConfig.DEBUG) {
            viewPager.setAdapter(new FragmentStateAdapter(getChildFragmentManager(), getLifecycle()) {
                @NonNull
                @Override
                public Fragment createFragment(int position) {
                    switch (position) {
                        case 0:
                            return new ChatsFragment();
                        case 1:
                            return new MessageFunctionFragment();
                    }
                    return null;
                }

                @Override
                public int getItemCount() {
                    return 2;
                }
            });
        } else {
            viewPager.setAdapter(new FragmentStateAdapter(getChildFragmentManager(), getLifecycle()) {
                @NonNull
                @Override
                public Fragment createFragment(int position) {
                    switch (position) {
                        case 0:
                            return new ChatsFragment();
                    }
                    return null;
                }

                @Override
                public int getItemCount() {
                    return 1;
                }
            });
        }

        TabLayoutMediator mediator = new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                TextView tv = new TextView(mContext);
                if (BuildConfig.DEBUG) {
                    switch (position) {
                        case 0:
                            tv.setText("消息");
                            break;
                        case 1:
                            tv.setText("发现");
                            break;
                    }
                } else {
                    switch (position) {
                        case 0:
                            tv.setText("消息");
                            break;
                    }
                }
                tv.setGravity(Gravity.CENTER);
                tv.setTextColor(ContextCompat.getColor(mContext, R.color.gray_light));
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                tab.setCustomView(tv);
            }
        });
        mediator.attach();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        List<Fragment> fragments = getChildFragmentManager().getFragments();
        for (Fragment fragment : fragments) {
            fragment.onHiddenChanged(hidden);
        }
    }
}






































































